<?php

include_once 'HelperDAO.class.php';

class GenericDAO {

    /**
     * @var $helperDAO HelperDAO
     */
    private $helperDAO;
    private $debugMode=false;

    /**
     *
     */
    function __construct($config=false) {
        $this->helperDAO = new HelperDAO($config);
        $this->debugMode = $config;
    }

    function get($tableName,$id){
        return $this->helperDAO->select("SELECT * FROM %s WHERE id = %s ", array($tableName,$id),true);
    }
    
    function getWhere($tableName,$where){
        return $this->helperDAO->select("SELECT * FROM %s WHERE %s", array($tableName,$where),true);
    }
    function listAll($tableName){
        return $this->helperDAO->select("SELECT * FROM %s", array($tableName));
    }

    function listAllWhere($tableName,$where){
        return $this->helperDAO->select("SELECT * FROM %s WHERE %s", array($tableName,$where));
    }

    function edit($tableName,$array,$where){
        $sql = "UPDATE %s set ";
        $paramArray[]=$tableName;
        $i=0;
        foreach($array as $key => $value){
            if($i++ !=0){
                $sql.=",";    
            }
            $sql.= " %s = '%s' ";
            $paramArray = array_merge($paramArray, array($key,$value));
        }
        $sql .= " WHERE ".$where;
        $paramArray = array_merge($paramArray, (array)$where);
        if($this->debugMode){
            echo '<br/><br/> Update statement : '.$sql."<br/><br/>";
            echo '<br/><br/> Update array: ';
            print_r($paramArray);
            echo '<br/><br/><br/><br/>';
        }
        return $this->helperDAO->update($sql, $paramArray);
    }

    function save($tableName,$array){
        $sql = "INSERT INTO %s ( ";
        $paramArray[]=$tableName;
        $i=0;
        $valuesArray;
        $values = "";
        foreach($array as $key => $value){
            if($i++ !=0){
                $sql.=",";
                $values.=",";
                $valuesArray = array_merge($valuesArray, (array)$value);
            }else
                $valuesArray[]=$value;
            $sql.= " %s";
            $values.= " '%s' ";
            $paramArray = array_merge($paramArray, (array)$key);
            
        }
        $sql .= " ) VALUES ( ".$values." )";
        $paramArray = array_merge((array)$paramArray, (array)$valuesArray);
        if($this->debugMode){
            echo '<br/><br/> Insert statement : '.$sql."<br/><br/>";
            echo '<br/><br/> Insert array: ';
            print_r($paramArray);
            echo '<br/><br/><br/><br/>';
        }
        return $this->helperDAO->insert($sql, $paramArray);
    }

    function delete($tableName,$where){
        return $this->helperDAO->delete("DELETE FROM  %s WHERE %s", array($tableName,$where));
    }

}